package snu.bi.MSAgent.DB;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class MSADBHandler{
	
	public static final String DB_NAME = "msr_learning_middle2.db";
	public String DB_PATH = null;
	public static final int DB_VERSION = 1;
	
	private static MSADBHandler instance = null;
	public SQLiteDatabase db;
	
	private int openCount;
	
	String svm_name = "model2.txt";
		
	public static MSADBHandler open(Context c){
		//if ( MSADBHandler.instance == null ){
			MSADBHandler.instance = new MSADBHandler(c);
		//}
		//MSADBHandler.instance.openCount += 1;
		return MSADBHandler.instance;
	}
	
	public void close(){
		//if ( this.openCount == 1 ){
			this.db.close();
		//}
		//this.openCount -= 1;
	}
	private boolean svm_download() {
		this.DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/snu.bi.MSAgent";
		String FULLPATH = DB_PATH + "/" + svm_name;
		
		File dir = new File(DB_PATH);
		File target = new File(FULLPATH);
		String svmpath = target.getAbsolutePath();
		
		if ( target.exists() ){
			return true;
		}else{
			// copy from internet			
			Log.d("DB FILE", "DOWNLOAD PURE SVM FROM INTERNET TO : " + target);
			
			try{
				URL url = new URL("http://bimsr.googlecode.com/files/"+svm_name);				
				URLConnection connection = url.openConnection();
				int length = connection.getContentLength();
				
				InputStream is = null;
	 			FileOutputStream fos = null;
	 			BufferedOutputStream bos = null;
	 			boolean success = false;
	 			
	 			try{
	 				boolean downloadFlag;
		 			int tmpLength = 0;
	 				
	 				is = connection.getInputStream();		 				
	 						 				
	 				if(!dir.exists()) dir.mkdirs();
	 				
	 				fos = new FileOutputStream(target);
	 				bos = new BufferedOutputStream(fos);
	 				
	 				byte[] buf = new byte[1024];
	 				downloadFlag = true;
	 				int l = 0;
	 				while((l=is.read(buf))>0){
	 					tmpLength += l;
	 					if(!downloadFlag) break;
	 					bos.write(buf, 0, l);		 					
	 				}
	 				success = true;
	 				
	 			}catch(Exception e){
	 				e.printStackTrace();
	 			}finally{
	 				try{bos.close();}catch(Exception e){}
	 				try{fos.close();}catch(Exception e){}
	 				try{is.close();}catch(Exception e){}
	 				
	 				//wakeLock.release();
	 			}
	 			return true;
			}catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	private MSADBHandler(Context c){
		svm_download();
		//thread??
		this.openCount = 0;
		
		this.DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/snu.bi.MSAgent";
		String FULLPATH = DB_PATH + "/" + MSADBHandler.DB_NAME;
		
		File dir = new File(DB_PATH);
		File target = new File(FULLPATH);
		String dbpath = target.getAbsolutePath();
		
		if ( target.exists() ){
			this.db = c.openOrCreateDatabase(target.getAbsolutePath(), Context.MODE_PRIVATE, null);
		}else{
			// copy from internet			
			Log.d("DB FILE", "DOWNLOAD PURE DB FROM INTERNET TO : " + target);
			
			try{
				URL url = new URL("http://bimsr.googlecode.com/files/"+DB_NAME);
				//URL url = new URL("http://bi.snu.ac.kr");
				URLConnection connection = url.openConnection();
				int length = connection.getContentLength();
				
				InputStream is = null;
	 			FileOutputStream fos = null;
	 			BufferedOutputStream bos = null;
	 			boolean success = false;
	 			
	 			try{
	 				boolean downloadFlag;
		 			int tmpLength = 0;
	 				
	 				is = connection.getInputStream();		 				
	 						 				
	 				if(!dir.exists()) dir.mkdirs();
	 				
	 				fos = new FileOutputStream(target);
	 				bos = new BufferedOutputStream(fos);
	 				
	 				byte[] buf = new byte[1024];
	 				downloadFlag = true;
	 				int l = 0;
	 				while((l=is.read(buf))>0){
	 					tmpLength += l;
	 					if(!downloadFlag) break;
	 					bos.write(buf, 0, l);		 					
	 				}
	 				success = true;
	 				
	 			}catch(Exception e){
	 				e.printStackTrace();
	 			}finally{
	 				try{bos.close();}catch(Exception e){}
	 				try{fos.close();}catch(Exception e){}
	 				try{is.close();}catch(Exception e){}
	 				this.db = c.openOrCreateDatabase(target.getAbsolutePath(), Context.MODE_PRIVATE, null);
	 				//wakeLock.release();
	 			}
				
			}catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public Cursor rawQuery(String query){
		Cursor t = this.db.rawQuery(query, null);
		return t;
	}
	public boolean clear_table(String tablename) {
		return db.delete(tablename, null, null) > 0;
	}
	public long insert(String table, String nullColumnHack, ContentValues values) {	
		return db.insert(table, nullColumnHack, values);
	}
	public String getPath() {
		return DB_PATH + "/" + MSADBHandler.DB_NAME;
	}
}

class MSADBHelper extends SQLiteOpenHelper{

	public MSADBHelper(Context context){
		super(context, MSADBHandler.DB_NAME, null, MSADBHandler.DB_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	
}
